package mx.groovy;

import java.io.File;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
import groovy.lang.Writable;
import groovy.text.Template;
import groovy.text.markup.MarkupTemplateEngine;
import groovy.text.markup.TemplateConfiguration;
import mx.setup.Setup;

import org.codehaus.groovy.runtime.ResourceGroovyMethods;

public class GUtils {
	private static GroovyClassLoader classLoader = new GroovyClassLoader();
	
	public static Script createGroovy(String filename, String encoding) throws Exception {
		File file = new File(filename);
		String text = ResourceGroovyMethods.getText(file, encoding);
		Class scriptClazz = classLoader.parseClass(text, filename);
		return (Script) scriptClazz.newInstance();
	}
	
	public static Script createGroovy(String text) throws Exception {
		Class scriptClazz = classLoader.parseClass(text);
		return (Script) scriptClazz.newInstance();
	}
	
	public static void mop() throws Exception {
		String filename =Setup.getConfigPath() + "/Mop.groovy";
		Object o = GUtils.createGroovy(filename, "GBK");
		Script script = (Script) o;
		script.run();
	}
	
	public String createFromTemplate(String tmp, Map data) throws Exception {
		TemplateConfiguration config = new TemplateConfiguration();         
		MarkupTemplateEngine engine = new MarkupTemplateEngine(config);     
		Template template = engine.createTemplate("p('test template')");             
		Writable output = template.make(data);   
		
		StringWriter writer = new StringWriter();
		output.writeTo(writer);
		return writer.toString();
	}
	
	public static void main(String args[]) throws Exception {
		Setup.initMain();
		String filename =Setup.getPath("forms") + "/grid/DemoTest.groovy";
		Object o = GUtils.createGroovy(filename, "utf-8");
		Script script = (Script) o;
		System.out.println(o);
	}
}
